using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;

namespace DocumentCreationSystem.Views;

/// <summary>
/// 创建项目对话框
/// </summary>
public partial class CreateProjectDialog : Window
{
    public string ProjectName { get; private set; } = string.Empty;
    public string ProjectType { get; private set; } = "Normal";
    public string ProjectPath { get; private set; } = string.Empty;
    public string ProjectDescription { get; private set; } = string.Empty;

    public CreateProjectDialog()
    {
        InitializeComponent();
        
        // 设置默认路径为用户文档目录下的DocumentCreation文件夹
        var defaultPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "DocumentCreation");
        ProjectPathTextBox.Text = defaultPath;
    }

    private void BrowsePathButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var folderDialog = new OpenFolderDialog
            {
                Title = "选择项目创建路径",
                Multiselect = false
            };

            // 如果当前路径有效，设置为初始路径
            if (!string.IsNullOrWhiteSpace(ProjectPathTextBox.Text) && Directory.Exists(ProjectPathTextBox.Text))
            {
                folderDialog.InitialDirectory = ProjectPathTextBox.Text;
            }

            if (folderDialog.ShowDialog() == true)
            {
                ProjectPathTextBox.Text = folderDialog.FolderName;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"选择路径时发生错误: {ex.Message}", "错误", 
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void CreateButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            // 验证输入
            if (string.IsNullOrWhiteSpace(ProjectNameTextBox.Text))
            {
                MessageBox.Show("请输入项目名称", "验证错误", 
                              MessageBoxButton.OK, MessageBoxImage.Warning);
                ProjectNameTextBox.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(ProjectPathTextBox.Text))
            {
                MessageBox.Show("请选择项目创建路径", "验证错误", 
                              MessageBoxButton.OK, MessageBoxImage.Warning);
                BrowsePathButton.Focus();
                return;
            }

            // 验证项目名称（不能包含非法字符）
            var invalidChars = Path.GetInvalidFileNameChars();
            if (ProjectNameTextBox.Text.Any(c => invalidChars.Contains(c)))
            {
                MessageBox.Show("项目名称包含非法字符，请重新输入", "验证错误", 
                              MessageBoxButton.OK, MessageBoxImage.Warning);
                ProjectNameTextBox.Focus();
                return;
            }

            // 验证路径是否存在
            if (!Directory.Exists(ProjectPathTextBox.Text))
            {
                var result = MessageBox.Show(
                    $"路径 '{ProjectPathTextBox.Text}' 不存在，是否创建？", 
                    "路径不存在", 
                    MessageBoxButton.YesNo, 
                    MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    try
                    {
                        Directory.CreateDirectory(ProjectPathTextBox.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"创建路径失败: {ex.Message}", "错误", 
                                      MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

            // 检查项目文件夹是否已存在
            var fullProjectPath = Path.Combine(ProjectPathTextBox.Text, ProjectNameTextBox.Text);
            if (Directory.Exists(fullProjectPath))
            {
                var result = MessageBox.Show(
                    $"项目文件夹 '{ProjectNameTextBox.Text}' 已存在，是否继续？", 
                    "文件夹已存在", 
                    MessageBoxButton.YesNo, 
                    MessageBoxImage.Question);

                if (result != MessageBoxResult.Yes)
                {
                    return;
                }
            }

            // 获取选中的项目类型
            if (ProjectTypeComboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                ProjectType = selectedItem.Tag?.ToString() ?? "Normal";
            }

            // 设置返回值
            ProjectName = ProjectNameTextBox.Text.Trim();
            ProjectPath = ProjectPathTextBox.Text.Trim();
            ProjectDescription = ProjectDescriptionTextBox.Text.Trim();

            DialogResult = true;
            Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"创建项目时发生错误: {ex.Message}", "错误", 
                          MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
        Close();
    }
}
